package edu.scau.cxq.gp.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import edu.scau.cxq.gp.common.annotation.ResponseResult;
import edu.scau.cxq.gp.common.result.MyResult;
import edu.scau.cxq.gp.common.utils.MD5Utils;
import edu.scau.cxq.gp.common.utils.WrapperUtils;
import edu.scau.cxq.gp.entity.dto.LoginDTO;
import edu.scau.cxq.gp.entity.dto.UserDTO;
import edu.scau.cxq.gp.entity.User;
import edu.scau.cxq.gp.service.IUserService;
import edu.scau.cxq.gp.entity.vo.UserVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @description 存储用户信息 前端控制器
 * @return
 * @author TLC
 */

@RestController
@ResponseResult
@RequestMapping("/user")
public class UserController {


    @Resource
    private IUserService userService;


    /**
     * sa-token
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    public Object login(@RequestBody LoginDTO loginDTO){


        //获取用户请求数据
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        //创建集合
        Map<String, Object> loginInfo = new HashMap<>();

        //业务层返回用户对象
        UserVO userVO = userService.getUser(username, password);

        //判断用户对象是否为空
        if (userVO == null) {
            return MyResult.fail(401, "账号或密码错误");
        }

        //判断用户对象是否冻结
        if (userVO.getUserHidden() == 1) {
            return MyResult.fail(411, "该账号已被冻结");
        }

        //判断用户类型
        String user = (userVO.getUserType() == 0 ? "SuperAdmin[" : "WarehouseAdmin[") + userVO.getUserAccount() + "]";



        StpUtil.login(user);
        String token = StpUtil.getTokenValueByLoginId(user);
        loginInfo.put("token", token);
        loginInfo.put("userInfo", userVO);
        //返回用户
        return loginInfo;
    }

    /**
     * 添加用户
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public boolean register(@RequestBody UserDTO userDTO) {
        return userService.registerUser(userDTO);
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @PostMapping("/logCheckPassword")
    public UserVO checkPassword(@RequestBody User user) {

        User userInfo = userService.checkUser(user);

        if (userInfo == null) {
            return null;
        }
        UserVO userVO = new UserVO();

        BeanUtils.copyProperties(userInfo, userVO);

        return userVO;
    }

    /**
     * 获取用户信息通过ID
     * @param userId
     * @return
     */
    @GetMapping("/logGetUserInfo")
    public UserVO getUserInfo(@Param("userId") String userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        return userVO;
    }

    /**
     * 修改用户信息
     * @return
     */
    @PostMapping("/logUpdateOne")
    public UserVO updateOne(@RequestBody UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        String salt = RandomStringUtils.randomAlphabetic(4);

        String password = MD5Utils.MD5Upper(user.getUserPasswd(), salt);

        user.setUserPasswd(password);
        user.setSalt(salt);
        user.setUserHidden(0);

//        return false;

        if(userService.updateById(user)) {
            UserVO vo = new UserVO();
            BeanUtils.copyProperties(user, vo);

            return vo;
        }

        return null;
    }


    /**
     * 退出登录
     * sa-token
     * @return
     */
    @PostMapping("/logout")
    public Map<String, Object> logout(@RequestBody Map<String, Object> tokenMap, HttpServletRequest httpServletRequest) {

        StpUtil.logoutByTokenValue((String) tokenMap.get("token"));
//        String loginId = (String) StpUtil.getLoginIdByToken((String) tokenMap.get("token"));
//        System.out.println(loginId);
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("msg", "成功退出");
        return resultMap;
    }

    /**
     * 分页查找用户
     * @return
     */
    @GetMapping("/selectByPage")
    public PageInfo<UserVO> selectByPage (Integer currentPage, Integer size, UserVO userVO) {
        PageInfo<UserVO> userVOList = userService.getUserVOList(currentPage, size,userVO);
        return userVOList;
    }

    /**
     * 删除（实际上是冻结）
     * @param user
     * @return
     */
    @PostMapping("/deleteOne")
    public boolean deleteOne(@RequestBody User user) {
        User find = userService.getById(user.getUserId());
        // 将隐藏位置1
        find.setUserHidden(1);
        return userService.updateById(find);
    }
    /**
     * 恢复（实际上是解锁）
     * @param user
     * @return
     */
    @PostMapping("/resumeOne")
    public boolean resumeOne(@RequestBody User user) {
        QueryWrapper queryWrapper = WrapperUtils.entitytoWrapper(user);
        user = userService.getOne(queryWrapper);
        // 将隐藏位置1
        user.setUserHidden(0);
        return userService.updateById(user);
    }
}
